<template>
  <div class="app-container" id="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="实习生" prop="internId">
        <el-select v-model="queryParams.internId"  placeholder="请选择实习生" @change="handleQuery">
          <el-option
            v-for="intern in internList"
            :key="intern.internId"
            :label="intern.studentName"
            :value="intern.internId"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="评分模板（企业）" prop="templateId">
        <el-select v-model="queryParams.templateId"  placeholder="请选择模版" @change="handleQuery">
          <el-option
            v-for="template in templateList"
            :key="template.templateId"
            :label="template.templateName"
            :value="template.templateId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="评分模板（教师）" prop="teaTemplateId">
        <el-select v-model="queryParams.teaTemplateId"  placeholder="请选择模版" @change="handleQuery">
          <el-option
            v-for="template in templateList"
            :key="template.templateId"
            :label="template.templateName"
            :value="template.templateId"
          />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="模板名称" prop="templateName">-->
<!--        <el-input-->
<!--          v-model="queryParams.templateName"-->
<!--          placeholder="请输入模板名称"-->
<!--          filterable clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="总分" prop="totalScore">-->
<!--        <el-input-->
<!--          v-model="queryParams.totalScore"-->
<!--          placeholder="请输入总分"-->
<!--          filterable clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="总满分" prop="totalMaxScore">-->
<!--        <el-input-->
<!--          v-model="queryParams.totalMaxScore"-->
<!--          placeholder="请输入总满分"-->
<!--          filterable clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="等级" prop="grade">
        <el-select v-model="queryParams.grade" placeholder="请选择等级" @change="handleQuery">
          <el-option
            v-for="dict in dict.type.collegeco_intern_evaluation_grade"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <!-- 更多查询条件-->
      <template v-if="isShowMore">
        <el-form-item label="用户" prop="userId">
          <el-select v-model="queryParams.userId"  placeholder="请选择用户" @change="handleQuery">
            <el-option
              v-for="user in userList"
              :key="user.userId"
              :label="user.userName"
              :value="user.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="员工" prop="empId">
          <el-select v-model="queryParams.empId"  placeholder="请选择员工" @change="handleQuery">
            <el-option
              v-for="emp in empList"
              :key="emp.empId"
              :label="emp.empName"
              :value="emp.empId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="评价人姓名" prop="evaluatorName">
          <el-input
            v-model="queryParams.evaluatorName"
            placeholder="请输入评价人姓名"
            filterable clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="评价人职位" prop="evaluatorPosition">
          <el-input
            v-model="queryParams.evaluatorPosition"
            placeholder="请输入评价人职位"
            filterable clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="评价日期" prop="evaluateTime">
          <el-date-picker filterable clearable
                          v-model="queryParams.evaluateTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择评价日期">
          </el-date-picker>
        </el-form-item>


      </template>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button :icon="isShowMore?'el-icon-d-arrow-right':'el-icon-d-arrow-left'" size="mini" type="warning" @click="isShowMore = !isShowMore">更多查询</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['collegeco:internEvaluation:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['collegeco:internEvaluation:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['collegeco:internEvaluation:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['collegeco:internEvaluation:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

<el-table v-loading="loading" :data="internEvaluationList" @selection-change="handleSelectionChange" stripe :height="tableHeight">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" width="55" label="序号" align="center" fixed/>
      <el-table-column label="鉴定ID" align="center" prop="evaluationId" />
<!--      <el-table-column label="实习生ID" align="center" prop="internId" />-->
<!--      <el-table-column label="用户ID" align="center" prop="userId" />-->
<!--      <el-table-column label="员工ID" align="center" prop="empId" />-->
<!--      <el-table-column label="使用的评分模板ID" align="center" prop="templateId" />-->
      <el-table-column label="模板名称" align="center" prop="templateName" width="250"/>

  <el-table-column label="自我鉴定" align="center" width="200">
    <template #default="scope">
      <el-tooltip placement="top" :open-delay="400" :enterable="true">
        <!-- Tooltip 内容：支持 HTML 渲染 -->
        <div slot="content" v-html="scope.row.selfEvaluation"></div>
        <!-- 单元格显示：最多3行，超出省略 -->
        <div class="cell-html-ellipsis" v-html="scope.row.selfEvaluation"></div>
      </el-tooltip>
    </template>
  </el-table-column>

      <el-table-column label="总分" align="center" prop="totalScore" />
      <el-table-column label="总满分" align="center" prop="totalMaxScore" />
      <el-table-column label="等级" align="center" prop="grade">
      <template slot-scope="scope">
        <dict-tag :options="dict.type.collegeco_intern_evaluation_grade" :value="scope.row.grade"/>
      </template>
      </el-table-column>
      <el-table-column label="单位综合意见" align="center" prop="companyOpinion" width="200"/>
      <el-table-column label="评价人姓名" align="center" prop="evaluatorName" min-width="150"/>
      <el-table-column label="评价人职位" align="center" prop="evaluatorPosition" min-width="150"/>
      <el-table-column label="评价日期" align="center" prop="evaluateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.evaluateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
  <el-table-column label="状态" prop="status" width="150">
    <template slot-scope="scope">
      <el-tag
        size="small"
        :type="getStatusType(scope.row.status)"
      >
        {{ getStatusLabel(scope.row.status) }}
      </el-tag>
    </template>
  </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180" fixed="right">
        <template slot-scope="scope">
          <el-button
              size="mini"
              type="text"
              icon="el-icon-info"
              @click="handleInfo(scope.row)"
              v-hasPermi="['collegeco:internEvaluation:query']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['collegeco:internEvaluation:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['collegeco:internEvaluation:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改实习生成绩鉴定主对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="68%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
      <el-col :span="8">
        <el-form-item label="实习生" prop="internId">
          <el-select v-model="form.internId"  placeholder="请选择实习生" @change="handleQuery">
            <el-option
              v-for="intern in internList"
              :key="intern.internId"
              :label="intern.studentName"
              :value="intern.internId"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="用户" prop="userId">
          <el-select v-model="form.userId"  placeholder="请选择用户" @change="handleQuery">
            <el-option
              v-for="user in userList"
              :key="user.userId"
              :label="user.userName"
              :value="user.userId"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="员工" prop="empId">
          <el-select v-model="form.empId"  placeholder="请选择员工" @change="handleQuery">
            <el-option
              v-for="emp in empList"
              :key="emp.empId"
              :label="emp.empName"
              :value="emp.empId"
            />
          </el-select>
        </el-form-item>
      </el-col>
<!--      <el-col :span="8">-->
<!--        <el-form-item label="模板id" prop="templateId">-->
<!--          <el-select v-model="form.templateId"  placeholder="请选择模版" @change="handleTemplateChange">-->
<!--            <el-option-->
<!--              v-for="template in templateList"-->
<!--              :key="template.templateId"-->
<!--              :label="template.templateId"-->
<!--              :value="template.templateId"-->
<!--            />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--      </el-col>-->
      <el-col :span="8">
        <el-form-item label="评分模板（企业）" prop="templateId">
          <el-select v-model="form.templateId"  placeholder="请选择模版" @change="handleTemplateChange">
            <el-option
              v-for="template in templateList"
              :key="template.templateId"
              :label="template.templateName"
              :value="template.templateId"
            />
          </el-select>
        </el-form-item>
<!--            <el-form-item label="模板名称" prop="templateName">-->
<!--              <el-select v-model="form.templateName"  placeholder="请选择模版" @change="handleQuery">-->
<!--                <el-option-->
<!--                  v-for="template in templateList"-->
<!--                  :key="template.templateName"-->
<!--                  :label="template.templateName"-->
<!--                  :value="template.templateName"-->
<!--                />-->
<!--              </el-select>-->
<!--            </el-form-item>-->
      </el-col>
          <el-col :span="8">
            <el-form-item label="评分模板（教师）" prop="teaTemplateId">
              <el-select v-model="form.teaTemplateId"  placeholder="请选择模版" @change="handleTemplateChange">
                <el-option
                  v-for="template in templateList"
                  :key="template.templateId"
                  :label="template.templateName"
                  :value="template.templateId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
                <el-form-item label="自我鉴定" prop="selfEvaluation">
                  <el-input v-model="form.selfEvaluation" type="textarea" placeholder="请输入内容" />
                </el-form-item>
          </el-col>
<!--      <el-col :span="8">-->
<!--            <el-form-item label="总分" prop="totalScore">-->
<!--              <el-input v-model="form.totalScore"  placeholder="请输入总分" />-->
<!--            </el-form-item>-->
<!--      </el-col>-->
<!--      <el-col :span="8">-->
<!--            <el-form-item label="总满分" prop="totalMaxScore">-->
<!--              <el-input v-model="form.totalMaxScore"  placeholder="请输入总满分" />-->
<!--            </el-form-item>-->
<!--      </el-col>-->
<!--      <el-col :span="8">-->
<!--        <el-form-item label="等级" prop="grade">-->
<!--          <el-select v-model="queryParams.grade" placeholder="请选择等级">-->
<!--            <el-option-->
<!--              v-for="dict in dict.type.collegeco_intern_evaluation_grade"-->
<!--              :key="dict.value"-->
<!--              :label="dict.label"-->
<!--              :value="dict.value"-->
<!--            />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--      </el-col>-->
          <el-col :span="24">
                <el-form-item label="单位综合意见" prop="companyOpinion">
                  <el-input v-model="form.companyOpinion" type="textarea" placeholder="请输入内容" />
                </el-form-item>
          </el-col>
      <el-col :span="8">
            <el-form-item label="评价人姓名" prop="evaluatorName">
              <el-input v-model="form.evaluatorName"  placeholder="请输入评价人姓名" />
            </el-form-item>
      </el-col>
      <el-col :span="8">
            <el-form-item label="评价人职位" prop="evaluatorPosition">
              <el-input v-model="form.evaluatorPosition"  placeholder="请输入评价人职位" />
            </el-form-item>
      </el-col>
          <el-col :span="8">
                <el-form-item label="评价日期" prop="evaluateTime">
                  <el-date-picker filterable clearable
                    v-model="form.evaluateTime"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="请选择评价日期">
                  </el-date-picker>
                </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.collegeco_intern_evaluation_status"
                  :key="dict.value"
                  :label="dict.value"
                >
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 实习生成绩打分明细信息 -->
        <el-divider content-position="center" style="margin: 30px 0 15px;">
          <span style="font-size: 16px; font-weight: 500; color: #333;">实习生成绩打分明细（企业）</span>
        </el-divider>

        <!-- 操作按钮 -->
        <el-row :gutter="10" class="mb8" style="margin-bottom: 12px;">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddHrmInternEvalScore('company')">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteHrmInternEvalScore('company')">删除</el-button>
          </el-col>
        </el-row>

        <!-- 评分明细表格 -->
        <el-table
          :data="hrmInternEvalScoreList"
          :row-class-name="rowHrmInternEvalScoreIndex"
          @selection-change="handleHrmInternEvalScoreSelectionChange"
          ref="hrmInternEvalScore"
          :height="tableHeight"
          border
          stripe
          style="width: 100%; margin-bottom: 16px;"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" width="60">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column label="评分项名称" prop="itemName">
            <template slot-scope="scope">
              <el-input v-model="scope.row.itemName" placeholder="请输入名称" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="该项满分" width="150">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.maxScore"
                :min="0"
                :max="100"
                :step="1"
                :precision="0"
                :controls-only="false"
                size="small"
                style="width: 100%;"
              />
            </template>
          </el-table-column>
          <el-table-column label="权重" width="150">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.weight"
                :min="0"
                :max="1"
                :step="0.01"
                :precision="2"
                size="small"
                placeholder="0.00 ~ 1.00"
                style="width: 100%;"
              />
            </template>
          </el-table-column>
          <el-table-column label="实际得分" prop="score" width="120">
            <template slot-scope="scope">
              <el-input v-model.number="scope.row.score" placeholder="得分" size="small" />
            </template>
          </el-table-column>
        </el-table>

        <!-- 教师评分 -->
        <el-divider content-position="center" style="margin: 30px 0 15px;">
          <span style="font-size: 16px; font-weight: 500; color: #333;">实习生成绩打分明细（教师）</span>
        </el-divider>
        <!-- 教师评分操作按钮 -->
        <el-row :gutter="10" class="mb8" style="margin-bottom: 12px;">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddHrmInternEvalScore('teacher')">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteHrmInternEvalScore('teacher')">删除</el-button>
          </el-col>
        </el-row>
        <!-- 教师评分表格 -->
        <el-table
          :data="hrmInternEvalScoreTeacherList"
          :row-class-name="rowHrmInternEvalScoreIndex"
          @selection-change="handleHrmInternEvalScoreSelectionChange"
          ref="hrmInternEvalScoreTeacher"
          :height="tableHeight"
          border
          stripe
          style="width: 100%; margin-bottom: 30px;"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" width="60">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column label="评分项名称" prop="itemName">
            <template slot-scope="scope">
              <el-input v-model="scope.row.itemName" placeholder="请输入名称" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="该项满分" width="150">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.maxScore"
                :min="0"
                :max="100"
                :step="1"
                :precision="0"
                size="small"
                style="width: 100%;"
              />
            </template>
          </el-table-column>
          <el-table-column label="权重" width="150">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.weight"
                :min="0"
                :max="1"
                :step="0.01"
                :precision="2"
                size="small"
                style="width: 100%;"
              />
            </template>
          </el-table-column>
          <el-table-column label="实际得分" prop="score" width="120">
            <template slot-scope="scope">
              <el-input v-model.number="scope.row.score" placeholder="得分" size="small" />
            </template>
          </el-table-column>
        </el-table>

        <!-- 总分统计（醒目提示） -->
        <el-alert
          title="总分统计"
          type="info"
          :closable="false"
          show-icon
          style="font-size: 15px; padding: 12px 20px; background-color: #f7f9fc; border: 1px solid #eaeef5;"
        >
          <template slot="title">
            <span style="font-weight: 600; color: #1f2d3d;">总分统计：</span>
            <!-- 企业评分 -->
            <span style="margin-right: 30px;">
              <strong>企业评分：</strong>
              <span style="color: #f56c6c; font-size: 16px;">{{ enterpriseTotalScore || 0 }}</span>
              <span>/</span>
              <span style="color: #409eff; font-size: 16px;">{{ enterpriseTotalMaxScore || 0 }}</span>
            </span>

            <!-- 教师评分 -->
            <span style="margin-right: 30px;">
              <strong>教师评分：</strong>
              <span style="color: #f56c6c; font-size: 16px;">{{ teacherTotalScore || 0 }}</span>
              <span>/</span>
              <span style="color: #409eff; font-size: 16px;">{{ teacherTotalMaxScore || 0 }}</span>
            </span>

            <!-- 评分 -->
            <span style="margin-right: 30px;">
              <strong>总分：</strong>
              <span style="color: #f56c6c; font-size: 16px;">{{ form.totalScore || 0 }}</span>
              <span>/</span>
              <span style="color: #409eff; font-size: 16px;">{{ form.totalMaxScore || 0 }}</span>
            </span>

            <span style="margin-right: 30px;">
              <strong>等级：</strong>
                <el-tag size="small" type="success" v-if="form.grade === '优秀'">优秀</el-tag>
                <el-tag size="small" type="primary" v-else-if="form.grade === '良好'">良好</el-tag>
                <el-tag size="small" type="warning" v-else-if="form.grade === '合格'">合格</el-tag>
                <el-tag size="small" type="danger" v-else-if="form.grade === '不合格'">不合格</el-tag>
            </span>
          </template>
        </el-alert>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 实习生成绩鉴定详情对话框（平铺式卡片模板） -->
    <el-dialog
      :title="title"
      :visible.sync="openInfo"
      width="78%"
      append-to-body
      :close-on-click-modal="false"
      @close="cancel"
    >
      <div class="intern-evaluation-detail-container">
        <!-- 模块1：实习生基本信息 -->
        <el-card shadow="hover" class="detail-card">
          <div slot="header" class="card-header">
            <span style="font-weight: 600; font-size: 16px; color: #1890ff; margin-left: 6px;">👤 实习生基本信息</span>
          </div>
          <el-row :gutter="20" class="detail-row">
            <el-col :span="8"><strong>实习生姓名：</strong> {{ studentName || '—' }}</el-col>
            <el-col :span="8"><strong>用户账号：</strong> {{ userName || '—' }}</el-col>
            <el-col :span="8"><strong>员工姓名：</strong> {{ empName || '—' }}</el-col>
          </el-row>
          <el-row :gutter="20" class="detail-row">
            <el-col :span="8"><strong>学号：</strong> {{ currentIntern.studentNo || '—' }}</el-col>
            <el-col :span="8"><strong>学校：</strong> {{ currentIntern.school || '—' }}</el-col>
            <el-col :span="8"><strong>学院：</strong> {{ currentIntern.college || '—' }}</el-col>
          </el-row>
          <el-row :gutter="20" class="detail-row">
            <el-col :span="8"><strong>专业：</strong> {{ currentIntern.major || '—' }}</el-col>
            <el-col :span="8"><strong>班级：</strong> {{ currentIntern.className || '—' }}</el-col>
            <el-col :span="8"><strong>实习单位：</strong> {{ currentIntern.internshipCompany || '—' }}</el-col>
          </el-row>
          <el-row :gutter="20" class="detail-row">
            <el-col :span="8"><strong>实习岗位：</strong> {{ currentIntern.internshipPosition || '—' }}</el-col>
            <el-col :span="8"><strong>实习开始：</strong> {{ parseTime(currentIntern.internshipStart, '{y}-{m}-{d}') || '—' }}</el-col>
            <el-col :span="8"><strong>实习结束：</strong> {{ parseTime(currentIntern.internshipEnd, '{y}-{m}-{d}') || '—' }}</el-col>
          </el-row>
          <el-row :gutter="20" class="detail-row">
            <el-col :span="8"><strong>学校导师：</strong> {{ currentIntern.instructorTeacher || '—' }}</el-col>
            <el-col :span="8"><strong>企业导师：</strong> {{ currentIntern.enterpriseMentor || '—' }}</el-col>
          </el-row>
        </el-card>

        <!-- 模块2：成绩鉴定主信息 -->
        <el-card shadow="hover" class="detail-card">
          <div slot="header" class="card-header">
            <span style="font-weight: 600; font-size: 16px; color: #faad14; margin-left: 6px;">📊 成绩鉴定基本信息</span>
          </div>
          <el-row :gutter="20" class="detail-row">
            <el-col :span="8"><strong>评分模板：</strong> {{ form.templateName || '—' }}</el-col>
            <el-col :span="8"><strong>总分：</strong> {{ form.totalScore }} / {{ form.totalMaxScore }}</el-col>
            <el-col :span="8"><strong>等级：</strong>
<!--              <dict-tag :options="dict.type.collegeco_intern_evaluation_grade" :value="form.grade"/>-->
              {{ form.grade }}
            </el-col>
          </el-row>
          <el-row :gutter="20" class="detail-row">
            <el-col :span="8"><strong>评价人：</strong> {{ form.evaluatorName || '—' }}</el-col>
            <el-col :span="8"><strong>职位：</strong> {{ form.evaluatorPosition || '—' }}</el-col>
            <el-col :span="8"><strong>评价日期：</strong> {{ parseTime(form.evaluateTime, '{y}-{m}-{d}') || '—' }}</el-col>
          </el-row>
          <el-row :gutter="20" class="detail-row">
            <el-col :span="24"><strong>自我鉴定：</strong> {{ form.selfEvaluation || '无' }}</el-col>
          </el-row>
          <el-row :gutter="20" class="detail-row">
            <el-col :span="24"><strong>单位综合意见：</strong> {{ form.companyOpinion || '无' }}</el-col>
          </el-row>
        </el-card>

        <!-- 模块3：企业评分明细 -->
        <el-card shadow="hover" class="detail-card">
          <div slot="header" class="card-header">
            <span style="font-weight: 600; font-size: 16px; color: #13c2c2; margin-left: 6px;">🏢 实习生成绩打分明细（企业）</span>
          </div>
          <el-table :data="hrmInternEvalScoreList" size="small" :row-class-name="rowHrmInternEvalScoreIndex">
            <el-table-column label="序号" align="center" type="index" width="50"/>
            <el-table-column label="评分项名称" prop="itemName" />
            <el-table-column label="该项满分" prop="maxScore" width="120" />
            <el-table-column label="权重" prop="weight" width="100" />
            <el-table-column label="实际得分" prop="score" width="120" />
          </el-table>
        </el-card>

        <!-- 模块4：教师评分明细 -->
        <el-card shadow="hover" class="detail-card">
          <div slot="header" class="card-header">
            <span style="font-weight: 600; font-size: 16px; color: #722ed1; margin-left: 6px;">🎓 实习生成绩打分明细（教师）</span>
          </div>
          <el-table :data="hrmInternEvalScoreTeacherList" size="small" :row-class-name="rowHrmInternEvalScoreIndex">
            <el-table-column label="序号" align="center" type="index" width="50"/>
            <el-table-column label="评分项名称" prop="itemName" />
            <el-table-column label="该项满分" prop="maxScore" width="120" />
            <el-table-column label="权重" prop="weight" width="100" />
            <el-table-column label="实际得分" prop="score" width="120" />
          </el-table>
        </el-card>
      </div>

      <!-- 对话框底部按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="openInfo = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInternEvaluation, getInternEvaluation, delInternEvaluation, addInternEvaluation, updateInternEvaluation } from "@/api/collegeco/internEvaluation";
import {listIntern} from "@/api/collegeco/intern";
import {listUser}  from "@/api/system/user";
import {listInternTemplate, getTemplateItems} from "@/api/collegeco/internTemplate";
import {listEmployee} from "@/api/hrm/employee";

export default {
  name: "InternEvaluation",
  dicts:['collegeco_eval_template_status' , 'collegeco_intern_evaluation_grade','collegeco_intern_evaluation_status'],
  data() {
    return {
      // 是否显示更多
      isShowMore: false,
      // el-table 高度
      tableHeight: 650, // 用于存储 el-table 的高度
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedHrmInternEvalScore: [],
      // 子表选中数据
      checkedHrmEvalTemplate: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 实习生成绩鉴定主表格数据
      internEvaluationList: [],
      // 实习生成绩打分明细表格数据（企业）
      hrmInternEvalScoreList: [],
      // 实习生成绩打分明细表格数据（教师）
      hrmInternEvalScoreTeacherList: [],
      // 实习评分标准模板库（主）表格数据
      hrmEvalTemplateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示详情弹出层
      openInfo: false,
      currentIntern: {}, // 当前选中的实习生信息
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        internId: null,
        userId: null,
        empId: null,
        templateId: null, // 企业评分模板ID
        teaTemplateId: null,  // 教师评分模板ID
        templateName: null,
        selfEvaluation: null,
        totalScore: null,
        totalMaxScore: null,
        grade: null,
        companyOpinion: null,
        evaluatorName: null,
        evaluatorPosition: null,
        evaluateTime: null,
        status: null,
      },
      // 企业评分
      enterpriseTotalScore: 0,
      enterpriseTotalMaxScore: 0,
      // 教师评分
      teacherTotalScore: 0,
      teacherTotalMaxScore: 0,
      // 表单参数
      form: {
        internId: null,      // 实习生ID
        templateId: null,
        userId: null,         // 用户ID
        templateName: null,
      },
      // 表单校验
      rules: {
        internId: [
          { required: true, message: "实习生ID不能为空", trigger: "blur" }
        ],
        userId: [
          { required: true, message: "用户ID不能为空", trigger: "blur" }
        ],
        templateId: [
          { required: true, message: "模板id不能为空", trigger: "blur" }
        ],
        templateName: [
          { required: true, message: "模板名称不能为空", trigger: "blur" }
        ],
      },
      // 实习生信息表格数据
      internList: [],
      // 用户表格数据
      userList: [],
      // 实习评分标准模板库（主）表格数据
      templateList: [],
      // 员工信息表格数据
      empList: [],
    };
  },
  created() {
    this.getList();
    this.setTableHeight();
    window.addEventListener('resize', this.setTableHeight); // 监听窗口大小变化

    // 初始获取实习生信息
    this.getInternList();
    // 初始获取用户信息
    this.getUserList();
    // 初始获取实习评分标准模板库（主）信息
    this.getTemplateList();
    // 初始获取员工信息
    this.getEmpList();
    console.log('API返回数据:', res.data); // 调试
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.setTableHeight); // 移除事件监听
  },
  watch: {
    //监听评分列表变化，自动计算
    hrmInternEvalScoreList: {
      handler() {
        this.calculateTotalScore();
      },
      deep: true  // 必须 deep: true 才能监听到 score 的变化
    },
    hrmInternEvalScoreTeacherList: {
      handler() {
        this.calculateTotalScore();
      },
      deep: true  // 必须 deep: true 才能监听到 score 的变化
    }
  },

  computed: {
    studentName() {
      const intern = this.internList.find(item =>
        String(item.internId) === String(this.form.internId)
      );
      return intern ? intern.studentName : '未知实习生';
    },
    userName(){
      const user = this.userList.find(item =>
        String(item.userId) === String(this.form.userId)
      );
      return user ? user.userName : '未知用户';
    },
    empName(){
      const emp = this.empList.find(item =>
        String(item.empId) === String(this.form.empId)
      );
      return emp ? emp.empName : '未知员工';
    },
    // 企业评分项
    hrmInternEvalScoreList() {
      return this.hrmInternEvalScoreList.filter(item => item.type === 'company');
    },
    // 教师评分项
    hrmInternEvalScoreTeacherList() {
      return this.hrmInternEvalScoreTeacherList.filter(item => item.type === 'teacher');
    }
  },

  methods: {
    showInternDetailById(internId) {
      const intern = this.internList.find(item => item.internId == internId);

      if (intern) {
        this.currentIntern = intern;
        this.openInternInfo = true;
      } else {
        this.$message.warning('未找到该实习生的详细信息');
      }
    },

    // 根据 value 返回字典 label
    getStatusLabel(value) {
      console.log('当前 status 值:', value, '类型:', typeof value);
      const strValue = String(value);
      const dict = this.dict.type.collegeco_intern_evaluation_status.find(item => item.value === strValue);
      return dict ? dict.label : '未知状态';
    },
    getStatusType(value) {
      switch (value) {
        case '1': return 'info';     // 待提交
        case '2': return 'warning';  // 审核中
        case '3': return 'success';  // 已通过
        default: return 'info';
      }
    },

    // 计算总分
    calculateTotalScore() {
      let total = 0;
      let maxTotal = 0;
      let enterpriseTotal = 0;
      let enterpriseMaxTotal = 0;
      let teacherTotal = 0;
      let teacherMaxTotal = 0;

      // 计算企业评分
      this.hrmInternEvalScoreList.forEach(item => {
        const score = parseFloat(item.score) || 0;
        const weight = parseFloat(item.weight) || 0;
        const maxScore = parseFloat(item.maxScore) || 0;

        enterpriseTotal += score * weight;
        enterpriseMaxTotal += maxScore * weight;
      });

      // 计算教师评分
      this.hrmInternEvalScoreTeacherList.forEach(item => {
        const score = parseFloat(item.score) || 0;
        const weight = parseFloat(item.weight) || 0;
        const maxScore = parseFloat(item.maxScore) || 0;

        teacherTotal += score * weight;
        teacherMaxTotal += maxScore * weight;
      });

      // 计算总分（enterpriseTotal和teacherTotal各占50%）
      total = (enterpriseTotal + teacherTotal) / 2;
      maxTotal = (enterpriseMaxTotal + teacherMaxTotal) / 2;

      // 存储各自的总分
      this.enterpriseTotalScore = enterpriseTotal.toFixed(2);
      this.enterpriseTotalMaxScore = enterpriseMaxTotal.toFixed(2);
      this.teacherTotalScore = teacherTotal.toFixed(2);
      this.teacherTotalMaxScore = teacherMaxTotal.toFixed(2);

      // 存储总分
      this.form.totalScore = total.toFixed(2);
      this.form.totalMaxScore = maxTotal.toFixed(2);

      // 自动评级
      this.autoGrade();
    },

    // 自动评级
    autoGrade() {
      if (!this.form.totalScore || !this.form.totalMaxScore) return;

      const percentage = (this.form.totalScore / this.form.totalMaxScore) * 100;

      if (percentage >= 90) {
        this.form.grade = '优秀';
      } else if (percentage >= 80) {
        this.form.grade = '良好';
      } else if (percentage >= 60) {
        this.form.grade = '合格';
      } else {
        this.form.grade = '不合格';
      }
    },
    // 根据模板ID获取评分项明细
    getTemplateItems(templateId) {
      return getTemplateItems(templateId)
    },
    // 模板选择变化时触发
    async handleTemplateChange(templateId) {
      if (!templateId) {
        this.hrmInternEvalScoreList = [];
        this.hrmInternEvalScoreTeacherList = [];
        this.form.totalScore = '0.00';
        this.form.totalMaxScore = '0.00';
        this.form.grade = '';
        return;
      }

      try {
        // 1. 获取选中的模板详情
        const template = this.templateList.find(t => t.templateId === templateId);
        if (template) {
          this.form.templateName = template.templateName;
        }

        // 2. 获取模板的评分项明细
        const response = await getTemplateItems(templateId);
        const items = response.data || [];

        // 3. 格式化评分项
        const formattedItems = items.map(item => ({
          itemId: item.itemId,
          itemName: item.itemName,
          maxScore: parseFloat(item.maxScore) || 0,
          weight: parseFloat(item.weight) || 0,
          score: "", // 实际得分初始为空
          description: item.description
        }));

        // // 4. 清空两个列表
        // this.hrmInternEvalScoreList = [];
        // this.hrmInternEvalScoreTeacherList = [];

        // 5. 👇 核心：根据模板名称关键词判断类型
        const name = template.templateName;

        if (
          name.includes('教师') ||
          name.includes('导师') ||
          name.includes('老师') ||
          name.includes('校内')
        ) {
          // → 教师评分模板
          this.hrmInternEvalScoreTeacherList = formattedItems;
        } else {
          // 默认：企业评分模板（包含 “企业”、“实习”、“岗位”、“单位” 等）
          this.hrmInternEvalScoreList = formattedItems;
        }

        // 6. 重新计算总分
        this.calculateTotalScore();

      } catch (error) {
        console.error("获取模板明细失败:", error);
        this.$message.error("加载模板明细失败");
        this.hrmInternEvalScoreList = [];
        this.hrmInternEvalScoreTeacherList = [];
      }
    },

    /** 查询实习生成绩鉴定主列表 */
    getList() {
      this.loading = true;
      listInternEvaluation(this.queryParams).then(response => {
        this.internEvaluationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取实习生信息 */
    getInternList(){
      listIntern(
        {
          pageNum: 1,
          pageSize: 10000,
        }).then(response => {
        this.internList = response.rows;
        console.log("internList",this.internList)

      });
    },
    getUserList(){
      listUser(
        {
          pageNum: 1,
          pageSize: 10000,
        }).then(response => {
        this.userList = response.rows;
        console.log("userList",this.userList)

      });
    },
    getTemplateList(){
      listInternTemplate(
        {
          pageNum: 1,
          pageSize: 10000,
        }).then(response => {
        this.templateList = response.rows;
        console.log("templateList",this.templateList)

      });
    },
    getEmpList(){
      listEmployee(
        {
          pageNum: 1,
          pageSize: 10000,
        }).then(response => {
        this.empList = response.rows;
        console.log("empList",this.empList)

      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openInfo = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        evaluationId: null,
        internId: null,
        userId: null,
        empId: null,
        templateId: null,
        teaTemplateId: null,
        templateName: null,
        selfEvaluation: null,
        totalScore: null,
        totalMaxScore: null,
        grade: null,
        companyOpinion: null,
        evaluatorName: null,
        evaluatorPosition: null,
        evaluateTime: null,
        status: null,
        createTime: null,
        updateTime: null
      };
      this.hrmInternEvalScoreList = [];
      this.hrmInternEvalScoreTeacherList = [];
      this.hrmEvalTemplateList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      console.log('查询参数:', this.queryParams);
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.evaluationId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加实习生成绩鉴定主";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const evaluationId = row.evaluationId || this.ids
      getInternEvaluation(evaluationId).then(response => {
        this.form = response.data;
        this.hrmInternEvalScoreList = (response.data.hrmInternEvalScoreList || [])
          .filter(item => item.type === 'company');
        this.hrmInternEvalScoreTeacherList = (response.data.hrmInternEvalScoreTeacherList || [])
          .filter(item => item.type === 'teacher');
        this.hrmEvalTemplateList = response.data.hrmEvalTemplateList;
        this.open = true;
        this.title = "修改实习生成绩鉴定主";
      });
    },
    /** 详情按钮操作 */
    handleInfo(row) {
      this.reset();
      const evaluationId = row.evaluationId || this.ids
      getInternEvaluation(evaluationId).then(response => {
        console.log("后端返回的数据：", response.data);
        this.form = response.data;
            this.hrmInternEvalScoreList = (response.data.hrmInternEvalScoreList || [])
              .filter(item => item.type === 'company');
            this.hrmInternEvalScoreTeacherList = (response.data.hrmInternEvalScoreTeacherList || [])
              .filter(item => item.type === 'teacher');
            this.hrmEvalTemplateList = response.data.hrmEvalTemplateList;
        this.openInfo = true;
        // 根据 form.internId 从 internList 中查找实习生信息
        const intern = this.internList.find(item => item.internId == this.form.internId);
        if (intern) {
          this.currentIntern = intern; // 填充 currentIntern
        } else {
          this.currentIntern = {}; // 或设置默认值
          console.warn('未找到 ID 为', this.form.internId, '的实习生信息');
        }
        this.title = "实习生成绩鉴定主详情";
        console.log('企业评分项:', this.hrmInternEvalScoreList);
        console.log('教师评分项:', this.hrmInternEvalScoreTeacherList);
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // ✅ 所有评分项都已经有 type 字段
          this.form.hrmInternEvalScoreList = this.hrmInternEvalScoreList;        // 每条 type='company'
          this.form.hrmInternEvalScoreTeacherList = this.hrmInternEvalScoreTeacherList; // 每条 type='teacher'

          const submitPromise = this.form.evaluationId
            ? updateInternEvaluation(this.form)
            : addInternEvaluation(this.form);

          submitPromise.then(() => {
            this.$modal.msgSuccess("操作成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const evaluationIds = row.evaluationId || this.ids;
      this.$modal.confirm('是否确认删除实习生成绩鉴定主编号为"' + evaluationIds + '"的数据项？').then(function() {
        return delInternEvaluation(evaluationIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
	/** 实习生成绩打分明细序号 */
    rowHrmInternEvalScoreIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 实习生成绩打分明细添加按钮操作 */
    handleAddHrmInternEvalScore(listType) {
      let list;
      let type;

      if (listType === 'company') {
        list = this.hrmInternEvalScoreList;
        type = 'company';
      } else if (listType === 'teacher') {
        list = this.hrmInternEvalScoreTeacherList;
        type = 'teacher';
      }

      list.push({
        itemName: '',
        maxScore: 0,
        weight: 0,
        score: null,
        type: type  // ✅ 关键：设置 type
      });
    },
    /** 实习生成绩打分明细删除按钮操作 */
    handleDeleteHrmInternEvalScore(listType) {
      let selected;
      if (listType === 'company') {
        selected = this.$refs.hrmInternEvalScore.selection;
        this.hrmInternEvalScoreList = this.hrmInternEvalScoreList.filter(
          item => !selected.includes(item)
        );
      } else if (listType === 'teacher') {
        selected = this.$refs.hrmInternEvalScoreTeacher.selection;
        this.hrmInternEvalScoreTeacherList = this.hrmInternEvalScoreTeacherList.filter(
          item => !selected.includes(item)
        );
      }
    },
    /** 复选框选中数据 */
    handleHrmInternEvalScoreSelectionChange(listType, selection) {
      if (listType === 'company') {
        this.selectedCompanyScores = selection;
      } else if (listType === 'teacher') {
        this.selectedTeacherScores = selection;
      }
    },

    /** 实习评分标准模板库（主）序号 */
    rowHrmEvalTemplateIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 实习评分标准模板库（主）添加按钮操作 */
    handleAddHrmEvalTemplate() {
      let obj = {};
      obj.templateName = "";
      obj.category = "";
      obj.applicableFor = "";
      obj.description = "";
      obj.status = "";
      obj.version = "";
      obj.isPublic = "";
      obj.createDept = "";
      this.hrmEvalTemplateList.push(obj);
    },
    /** 实习评分标准模板库（主）删除按钮操作 */
    handleDeleteHrmEvalTemplate() {
      if (this.checkedHrmEvalTemplate.length == 0) {
        this.$modal.msgError("请先选择要删除的实习评分标准模板库（主）数据");
      } else {
        const hrmEvalTemplateList = this.hrmEvalTemplateList;
        const checkedHrmEvalTemplate = this.checkedHrmEvalTemplate;
        this.hrmEvalTemplateList = hrmEvalTemplateList.filter(function(item) {
          return checkedHrmEvalTemplate.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleHrmEvalTemplateSelectionChange(selection) {
      this.checkedHrmEvalTemplate = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('hrm/internEvaluation/export', {
        ...this.queryParams
      }, `实习生成绩鉴定主数据导出_${new Date().getTime()}.xlsx`)
    },
    // 设置表格高度
    setTableHeight() {
      const appContainer = document.getElementById('app-container');
      if (appContainer) {
        this.tableHeight = appContainer.clientHeight * 0.8;
      }
    }
  }
};
</script>
<style>
/* 统一单元格样式：最多显示3行，超出隐藏，带省略号 */
.cell-html-ellipsis {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.5;
  max-height: 4.5em;
  padding: 2px 0;
  margin: 0;
  font-size: 14px;
  cursor: pointer;
  text-align: left; /* 如果内容左对齐更清晰 */
}

/* 优化 Tooltip 样式，支持 HTML 列表展示 */
.el-tooltip__popper {
  max-width: 400px;
  max-height: 300px;
  overflow-y: auto;
  word-break: break-word;
  line-height: 1.6;
  text-align: left;
  border-radius: 6px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
.el-tooltip__popper ul,
.el-tooltip__popper ol {
  margin: 8px 0;
  padding-left: 20px;
  margin-block-start: 0.3em;
  margin-block-end: 0.3em;
}
.el-tooltip__popper li {
  margin: 4px 0;
}
.el-tooltip__popper p {
  margin: 6px 0;
}
.el-tooltip__popper::-webkit-scrollbar {
  width: 6px;
}

.el-tooltip__popper::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.el-tooltip__popper::-webkit-scrollbar-thumb {
  background: #ccc;
  border-radius: 3px;
}

.el-tooltip__popper::-webkit-scrollbar-thumb:hover {
  background: #999;
}

.intern-evaluation-detail-container {
  max-height: 70vh;
  overflow-y: auto;
  padding: 10px;
}

.detail-card {
  margin-bottom: 16px;
  border-radius: 8px;
  font-size: 14px;
}

.card-header {
  font-size: 16px;
}

</style>

